import os.path
from PIL import Image

import flet as ft

from utils import snack_bar, DESKTOP
from views.treasure_dialogs.base import BaseDialog

class Dialog(BaseDialog):
    def __init__(self):
        self.close_btn = ft.IconButton(
            icon=ft.icons.CLOSE_OUTLINED, on_click=self.close_dlg
        )
        self.choose_file_dialog = None
        self.choose_file_btn = ft.FloatingActionButton(
            "请选择图片存放的文件夹", on_click=self.open_dialog, width=300
        )
        self.hint = ft.Text(
            "· 目前暂不支持扫描PDF文字识别\n"
            "· 仅支持从左向右书写的语言（因此不支持阿拉伯语）\n"
            "· 不支持旋转的文字\n"
            "· 基于规则的解析无法保证100%还原PDF样式\n"
        )
        self.content = ft.Column([self.choose_file_btn, self.hint])
        super(Dialog, self).__init__(
            title=ft.Text("img转pdf"),
            content=self.content,
            actions=[self.close_btn],
            actions_alignment="center",
        )

    def open_dialog(self, e):
        if self.choose_file_dialog is None:
            self.choose_file_dialog = ft.FilePicker(on_result=self.img2pdf_action)
            self.page.overlay.append(self.choose_file_dialog)
            self.page.update()
        self.choose_file_dialog.get_directory_path(dialog_title="选择图片文件夹",)

    def img2pdf_action(self, e: ft.FilePickerResultEvent):
        print("on_dialog_result")
        if e.path:
            print("Selected folder:", e.path)
            img_path = e.path
            file_list = os.listdir(img_path)
            self.close_dlg(None)
            # 显示进度条
            self.page.progress_bar.visible = True
            self.page.update()
            for x in file_list:
                print("file_list folder:", x)
                if "jpg" in x or 'png' in x or 'jpeg' in x:
                    pdf_name = x.split('.')[0]
                    im1 = Image.open(os.path.join(img_path, x))
                    im1.save(img_path + "/" + pdf_name + '.pdf', "PDF", resolution=100.0)
                else:
                    print("非图片文件不做处理")
            # 隐藏进度条
            self.page.progress_bar.visible = False
            self.page.update()
            snack_bar(self.page, f"转换完成，已保存")



